<?php

namespace app\modules\h5cargo\models;
use Yii;
use yii\base\Model;

use yii\base\Exception;
class JSSDK extends Model
{
    private $appId;
    private $appSecret;
    public function __construct()
    {
        $this->appId = "wxda610a73f463f6d5";
        $this->appSecret = "533e98b152f8d407b4ce2872121e02e5";
    }

    public function getSignPackage($api_url)
    {
        $jsapiTicket = $this->getJsApiTicket();
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        //$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $url=$api_url;
        //var_dump($url);exit;
        //$url = "http://test.chesudi.com/?g=Wap&m=Online&a=login";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        //echo($url);
        $signature = sha1($string);

        $signPackage = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string,
            "title" => "车速递-优惠券,分享后优惠多多"
        );
//        echo("<\br>");
//        echo($signature);
//        echo("<\br>");
//        echo($jsapiTicket);
//        echo("<\br>");
//        echo($timestamp);
//        echo("<\br>");
//        echo($url);
//        var_dump('');
        return $signPackage;
    }

    private function getJsApiTicket()
    {
        //$cache = yii::$app->cache;
        //$cache['jsapi_ticket'] = '123';

        //$expire_time = json_decode(S('expire_time'));
        if( yii::$app->cache->get("expire_time") == null || yii::$app->cache->get("expire_time") < time())
        {    $accessToken = $this->getAccessToken(1);
            // 如果是企业号用以下 URL 获取 ticket
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";

            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));

            $ticket = $res->ticket;
            if ($ticket) {
                $expire_time = time() + 7000;
                $jsapi_ticket = $ticket;
                //$this->set_php_file("tpl\WeChatActivity\default\jsapi_ticket.php", json_encode($data));
                yii::$app->cache->set("expire_time",$expire_time,7000);
                yii::$app->cache->set("jsapi_ticket",$jsapi_ticket,7000);

            }
        } else {
            $ticket= yii::$app->cache->get("jsapi_ticket");
        }
//        var_dump($expire_time);
//        var_dump($ticket);
//        exit;
        return $ticket;
    }

    private function get_php_file($filename)
    {
        return trim(substr(file_get_contents($filename), 15));
    }

    public function getAccessToken($flag = 0)
    {
        if ($flag == 1) {//主动生成最新token
            yii::$app->cache->set("expire_time1",null);
            yii::$app->cache->set("access_token1",null);
        }
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        //$data = json_decode($this->get_php_file("tpl\WeChatActivity\default\access_token.php"));


        if( yii::$app->cache->get("expire_time1") == null || yii::$app->cache->get("expire_time1") < time())
        {

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";

            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $expire_time1 = time() + 7000;
                $access_token1 = $access_token;
                yii::$app->cache->set("expire_time1",$expire_time1,7000);
                yii::$app->cache->set("access_token1",$access_token1,7000);

                //$this->set_php_file("tpl\WeChatActivity\default\access_token.php", json_encode($data));
            }
        }
        else {

            $access_token1 =yii::$app->cache->get("access_token1");
        }
        return $access_token1;
    }


    public function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    private function set_php_file($filename, $content)
    {
        $fp = fopen($filename, "w");
        fwrite($fp, "<?php exit();?>" . $content);
        fclose($fp);
    }

    public function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}

